package main

import (
	"encoding/json"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/go-vgo/robotgo"
	"github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func wsHandler(w http.ResponseWriter, r *http.Request) {
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Println(err)
		return
	}
	defer conn.Close()

	for {
		messageType, message, err := conn.ReadMessage()
		if err != nil {
			log.Println(err)
			break
		}
		if messageType == websocket.TextMessage {
			var data map[string]interface{}
			if err := json.Unmarshal(message, &data); err != nil {
				log.Println(err)
				continue
			}
			handleMouse(data)
		}
	}
}

func handleMouse(data map[string]interface{}) {
	action := data["action"].(string)
	switch action {
	case "down":
		robotgo.Click("left", true)
	case "up":
		robotgo.Click("left", false)
	case "move":
		x := int(data["x"].(float64))
		y := int(data["y"].(float64))
		robotgo.MoveMouse(x, y)
	default:
		log.Println("Unknown action:", action)
	}
}

func main() {
	router := gin.Default()
	router.LoadHTMLGlob("templates/*")

	// 首页路由
	router.GET("/", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.html", nil)
	})

	// WebSocket路由
	router.GET("/ws", func(c *gin.Context) {
		wsHandler(c.Writer, c.Request)
	})

	router.Run(":8080")
}
